package org.ll.web.controller;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ll.common.core.constant.SystemConstants;
import org.ll.common.core.domain.R;
import org.ll.common.core.domain.model.LoginBody;
import org.ll.common.core.utils.MessageUtils;
import org.ll.common.core.utils.StringUtils;
import org.ll.common.core.utils.ValidatorUtils;
import org.ll.common.json.utils.JsonUtils;
import org.ll.system.domain.vo.SysClientVo;
import org.ll.system.service.ISysClientService;
import org.ll.web.domain.vo.LoginVo;
import org.ll.web.service.IAuthStrategy;
import org.ll.web.service.SysLoginService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证
 *
 * @author ll
 * @date 2025/1/23 15:42
 */
@Tag(name = "认证")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final ISysClientService clientService;

    private final SysLoginService loginService;

    @Operation(summary = "登录")
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
        //解析参数
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        SysClientVo client = clientService.queryByClientId(clientId);

        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }

        // 登录
        LoginVo loginVo = IAuthStrategy.login(body,client,grantType);

        return R.ok(loginVo);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }
}
